<template>
  <div class="supervise-mine">
    <div v-show="isShowStatisticalToolBar"
         class="main-header">
      <StatisticTabsHeader v-model="currentChooseVal"
                           :tabsList="statisticListArr"
                           v-if="statisticListArr.length"
                           @handleChange="dataTypeChange">
      </StatisticTabsHeader>
    </div>
    <div class="main-content"
         :key="reloadIndex">
      <supervise :key="dataType"
                 :dataType="dataType"
                 :statisRecieveData="statisRecieveData"
                 :needStatisticsVal="needStatisticsVal"
                 @updadeStatisticsBar="updadeStatisticsBar"
                 v-if="dataType !== 'workflowBug'"></supervise>
      <workflow-bug :key="dataType"
                    :dataType="dataType"
                    :statisRecieveData="statisRecieveData"
                    :needStatisticsVal="needStatisticsVal"
                    @updadeStatisticsBar="updadeStatisticsBar"
                    v-else></workflow-bug>
    </div>
  </div>
</template>

<script>
  import StatisticTabsHeader from '@/components/statistic-tabs-header/index.vue';
  import Supervise from './src/supervise';
  import WorkflowBug from './src/workflow-bug';
  import { getParams } from '../../utils';
  import { formatRequestDataToJSON, loadExtendResource } from '@/utils/api';

  export default {
    name: 'SuperviseMine',
    components: {
      Supervise,
      WorkflowBug,
      StatisticTabsHeader
    },
    data() {
      return {
        urlParamObj: {},
        statisticListArr: [],
        isShowStatisticalToolBar: true, // 是否显示顶部的统计控件
        isShowTotal: true, // 是否显示统计控件的总数
        currentChooseVal: '',
        reloadIndex: 0,
        dataType: '',
        needStatisticsVal: false,
        statisRecieveData: null
      };
    },
    methods: {
      initPageMetaData({ callback } = {}) {
        const headerParams = {
          // 页面唯一标识（取值参照PageKey）
          key: 'SUPERVISE',
          // 终端 0 pc 1 mobile （取值参照PlatformType）
          platform: 0,
          // 业务传参，由业务决定（后续可在元数据拦截器中获取到）
          arguments: {
            managerType: this.urlParamObj.managerType,
            boardId: this.urlParamObj.boardId,
            needStatisticsVal: false // 是否是请求统计数量
          }
        };
        const url = `${window._ctxPath}/rest/global/metadata/list`;
        window.axios.post(url, headerParams).then((data) => {
          if (data.data.code === 0) {
            const recieveData = data.data.data;
            loadExtendResource(recieveData.extra?.extendResources);
            this.statisRecieveData = recieveData;
            this.initStatisticsBar(recieveData);
            callback && callback();
          }
        });
      },

      dataTypeChange(key) {
        if (this.currentChooseVal === key) {
          this.reloadIndex++;
        }
        this.currentChooseVal = key;
        this.dataType = key;
      },
      updadeStatisticsBar(data) {
        if (data) {
          this.initStatisticsBar(data);
        } else {
          this.initPageMetaData();
        }
      },
      initStatisticsBar(data) {
        const recieveData = data;
        this.globalParam = recieveData.globalParam || {};
        this.isShowStatisticalToolBar = this.globalParam.isShowStatisticalToolBar === '1';
        this.isShowTotal = this.globalParam.isShowTotal === '1';
        const statisticListShowMap = {
          all: this.globalParam.haveAll,
          done: this.globalParam.haveDone,
          overdue: this.globalParam.haveOverdue,
          pending: this.globalParam.havePending,
          workflowBug: this.globalParam.haveProcessException,
          sevenDayOverdue: this.globalParam.haveNoOverdue
        };
        const { sourceType, templateIds } = this.globalParam;
        const { templeteIds } = this.urlParamObj;
        let operationType = '';
        if (sourceType === 1) {
          operationType = 'self';
        }
        if (templeteIds || templateIds) {
          operationType = 'template';
        }
        const hideValueKeys = ['all', 'done', 'pending'];
        this.statisticListArr = recieveData.pageHead.items.filter((item) => {
          if (!this.isShowTotal) {
            item.hideValue = true;
          } else {
            if (hideValueKeys.includes(item.key)) {
              // 这几种类型不需要显示统计value
              item.hideValue = true;
            } else {
              item.hideValue = false;
            }
          }
          return statisticListShowMap[item.key];
        });

        var defaultValue = '';
        for (var item in statisticListShowMap) {
          if (statisticListShowMap[item]) {
            defaultValue = item;
            break;
          }
        }
        const sendParams = [
          {
            managerType: 'mySupervise',
            dataType: this.dataType || defaultValue,
            flowstate: '0',
            sourceType: sourceType !== null ? sourceType.toString() : '',
            status: '0',
            haveOverdue: this.globalParam.haveOverdue,
            haveNoOverdue: this.globalParam.haveNoOverdue,
            haveProcessException: this.globalParam.haveProcessException,
            operationType: operationType,
            operationTypeIds: this.urlParamObj.templeteIds || this.globalParam.templateIds || ''
          }
        ];
        const args = `managerMethod=getProcessSuperviseCountMap&arguments=${JSON.stringify(
          sendParams
        )}`;
        const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=affairManager&rnd=6714`;
        if (this.isShowStatisticalToolBar && this.isShowTotal) {
          window.axios
            .post(url, args, {
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
              }
            })
            .then((data, err) => {
              console.log(err, 'err');
              const result = data.data;
              this.statisticListArr = recieveData.pageHead.items.filter((item) => {
                if (hideValueKeys.includes(item.key)) {
                  // 这几种类型不需要显示统计value
                  item.hideValue = true;
                }
                if (result.hasOwnProperty(item.key)) {
                  item.value = result[item.key];
                }
                return statisticListShowMap[item.key];
              });
            });
        }
      }
    },
    created() {
      this.urlParamObj = getParams(window.location.search);
      this.initPageMetaData({
        callback: () => {
          let superviseBoxType = this.statisticListArr.length ? this.statisticListArr[0].key : 'all';
          const {quotaType} =  this.urlParamObj;
          this.dataType = superviseBoxType;
          this.currentChooseVal = superviseBoxType;
          if (quotaType === 'processException'){
              this.currentChooseVal = 'workflowBug';
              this.dataType = 'workflowBug';
          }
          this.needStatisticsVal = false;
        }
      });
    },
    mounted() {}
  };
</script>

<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss">
  .supervise-mine {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    background-color: #ffffff;

    * {
      box-sizing: border-box;
    }

    .main-content {
      // padding: 0 0 0 20px;
      position: relative;
      flex: 1;
      overflow: hidden;
    }
  }
</style>
